// Copyright 2022 marcello<volibearw@gmail.com>. All rights reserved.

package main

import (
	"fmt"
	"log"
	"os"
)

// generateProtobuf3
func generateProtobuf3(param *CLIParam, tables map[string][]Columns) {

	if !param.Proto {
		log.Println("跳过生成protobuf")
		return
	} else {
		log.Println("开始生成protobuf...")
	}

	var (
		protobufFile = "syntax = \"proto3\";\n"
		message      string
		err          error
	)
	protobufFile += "package " + param.ProtoPackage + ";\n"
	protobufFile += "option go_package = \"" + param.ProtoOptionGoPackage + "\";\n\n"

	if _, err = os.Stat(param.ProtoOut); err != nil {
		if err = os.MkdirAll(param.ProtoOut, os.ModePerm); err != nil {
			log.Println(err)
			log.Println("创建目录", param.ProtoOut, "失败")
			return
		}
	}

	for tableName, columns := range tables {
		message += "message " + toCamelString(tableName) + "{\n"
		for n, column := range columns {
			if isGormDefaultModelDeletedField(column.ColumnName) {
				// 跳过 gorm 默认deleted_at字段
				continue
			}
			if column.Comment != "" {
				column.Comment = "// " + column.Comment
			}
			message += fmt.Sprintf("    %s %s=%d; %s\n",
				column.ColumnProtoDataType, column.ColumnNameSnake, n+1, column.Comment)
		}
		message += "}\n\n"
	}
	protobufFile += message
	log.Println("生成文件: " + param.ProtoOut + "/model.proto")
	if err = writeFile(param.ProtoOut+"/model.proto", protobufFile); err != nil {
		log.Println(err)
	}
}
